module FdString where

import FdType
import FdArray
import FdUtil
import FdHelper

import Data.List
import Data.IORef
import Monad
import Control.Monad.Error
import System.IO.Unsafe(unsafePerformIO)

s_ = fd_new_string

fd_new_string :: String -> Fineday Val
fd_new_string str = fmap String $ makeArray str

fd_nil_string = fd_new_string ""

fd_string_is_nil [str] = do {
	str <- liftIO $ readIORef str;	
	return $ (length str) /= 0;
}

fd_get_string_elem :: [Val] -> Fineday Val
fd_get_string_elem [String str, Number i] = do {
    res <- getArrayItem str (round i);
    (case res of 
        Just c -> fd_new_string $ [c]
        Nothing   -> return Nil);
}

fd_get_string_elem paras = throwError $ ParamErr (length paras) 2

fd_set_string_elem :: [Val] -> Fineday Val 
fd_set_string_elem [String strRef, Number i, String c]   = do {
    c <- str_to_char c;
    setArrayItem strRef (round i) c; 
    fd_new_string [c];
}
fd_set_string_elem [_, _, _]                   = throwError $ TypeErr $ ""
fd_set_string_elem paras                       = throwError $ ParamErr (length paras) 3

fd_copy_string [String str] = fmap String $ copyArray str
fd_copy_string [_]          = throwError $ TypeErr $ "not String"
fd_copy_string paras        = throwError $ ParamErr (length paras) 1

fd_concat_string [String s1, String s2] = fmap String $ concatArray s1 s2
fd_concat_string [_, _]                 = throwError $ TypeErr $ "not String"
fd_concat_string paras                  = throwError $ ParamErr (length paras) 2

str_to_char str = do {
    res <- getArrayItem str 0;
    return (case res of 
        Just c -> c
        Nothing -> ' ');
}
